<?php
namespace app\channel\controller;
use think\Db;

class ChannelBelong extends Base
{
    //只有CPS渠道可以访问
    public function _initialize(){
        parent::_initialize();
        if(!session('admin.cps_id')){
            $this->error('访问错误');
        }
    }

    public function index(){
        if( request()->isAjax() ){
            $myUserName = input('my_user_name');
            $gameId = input('game_id');

            if(empty($myUserName) || empty($gameId)){
                $this->layTable();
            }

            $whereUser['my_user_name'] = $myUserName;
            $whereUser['channel_id'] = 1000;
            $find = Db::name('User')->field('reg_time, my_user_id')->where($whereUser)->find();

            if(!$find){
                $this->layTable();
            }

            $startTime = $find['reg_time'];
            $myUserId = $find['my_user_id'];
            $endTime = time();

            $whereGame = "my_user_id='{$myUserId}' && channel_id=1000 && game_id={$gameId}";

            //跨年分表
            $y1 = date('Y', $startTime);
            $y2 = date('Y', $endTime);

            $field = "my_user_id, channel_id, cps_id, game_id, bond_time";

            if($y2-$y1 == 2){ //跟现在查两年，查三个
                $subQuery = Db::name('GameUserY_'.$y1)
                    ->field($field)
                    ->where($whereGame)
                    ->union("select {$field} from sdk_game_user_y_2017 where ({$whereGame})", true)
                    ->union("select {$field} from sdk_game_user_y_{$y2} where ({$whereGame})", true)
                    ->buildSql();
                $cpsId = Db::table($subQuery.' y')
                    ->value('cps_id');
            }else if($y2-$y1 == 1){ //跟现在差一年，查两个
                $subQuery = Db::name('GameUserY_'.$y1)
                    ->field($field)
                    ->where($whereGame)
                    ->union("select {$field} from sdk_game_user_y_{$y2} where ({$whereGame})", true)
                    ->buildSql();
                $cpsId = Db::table($subQuery.' y')
                    ->value('cps_id');
            }else if($y1 == $y2){ //同一年查一个
                $cpsId = Db::name('GameUserY_'.$y1)
                    ->field($field)
                    ->where($whereGame)
                    ->value('cps_id');
            }

            $data[] = [
                'my_user_name' => $myUserName,
                'belong' => session('admin.cps_id')==$cpsId ? '归属' : '不归属'
            ];

            $this->layTable(0, '验证玩家归属“', $data);
        }else{
            $gameData = model('Base')->gameNotice();
            return view('', ['game_data'=>$gameData]);
        }
    }
}
